<template>
  <div class="upload-file">
    <el-upload multiple :action="url" :before-upload="handleBeforeUpload" :file-list="fileList" :accept="accept"
      :limit="limit" :on-error="handleUploadError" :on-remove="handleRemove" :on-exceed="handleExceed"
      :on-success="handleUploadSuccess" :show-file-list="true" :headers="headers" class="upload-file-uploader"
      ref="upload" :drag="drag" :http-request="customUpload" :list-type="listType">
      <!-- 上传按钮 -->
      <el-button v-show="!drag" size="small" type="primary">选取文件</el-button>
      <!-- 拖拽上传区域 -->
      <i v-show="drag" class="el-icon-upload"></i>
      <div v-show="drag" class="el-upload__text" style="padding: 0 10px">
        将文件拖到此处，或<em>点击上传</em>
      </div>
      <slot></slot>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize">
          大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
        </template>
        <template v-if="fileType">
          格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
        </template>
        的文件
      </div>
    </el-upload>
    <loadCom :loadTarget="load" :tips="'上传中'" />
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { putOssTempUrl, postOssUpload } from "@/api/oss";
import loadCom from "@/components/Load";
export default {
  name: "FileUpload",
  components: {
    loadCom,
  },
  props: {
    value: [String, Object, Array],
    limit: {
      type: Number,
      default: 1,
    },
    fileSize: {
      type: Number,
      default: 1024,
    },
    fileType: {
      type: Array,
      default: () => [],
    },
    url: {
      type: String,
      default: process.env.VUE_APP_BASE_API + "",
    },
    isShowTip: {
      type: Boolean,
      default: true,
    },
    accept: {
      type: String,
      default: "",
    },
    drag: {
      type: Boolean,
      default: true,
    },
    listType: {
      type: String,
      default: "text",
    },
    // 单页面多次引用区别是谁
    who: {
      type: String,
      default: "",
      required: false,
    },
    // 循环套用时候需要传入应用对象
    applyTarget: {
      type: Object,
      default: null,
      required: false,
    },
  },
  data() {
    return {
      // baseUrl: process.env.VUE_APP_BASE_API,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      uploadFile: null,
      uploadParams: {
        path: "",
        name: "",
        permission: "tenant",
        suffix: "",
        mediaType: "",
        sizeLimit: "",
        attachment: "",
      },
      ossId: "",
      dynamicHeaders: null,
      dynamicMethod: null,
      dynamicUrl: null,
      load: false,
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // console.log("文件列表:", val);
          let list = [];
          if (Array.isArray(val)) {
            list = val;
          } else if (typeof val === "object" && Object.keys(val).length > 0) {
            list = [val];
          } else if (typeof val === "string") {
            if (val.includes(",")) {
              list = val.split(",").filter((item) => item.trim());
            } else {
              list = [val];
            }
          }
          this.fileList = list.map((item) => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            return item;
          });
        } else {
          this.fileList = [];
        }
      },
      deep: false,
      immediate: true,
    },
  },
  computed: {
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  created() {
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
  },
  methods: {
    handleBeforeUpload(file) {
      // 根据获取的文件file的name属性的后缀名，判断是否是限制类型的文件
      if (this.fileType.length > 0) {
        const fileExtension = file.name.split(".").pop().toLowerCase();
        if (!this.fileType.includes(fileExtension)) {
          this.$message({
            message: "非限制类型文件，请重新选择",
            type: "warning",
          });
          return false;
        }
      }
      // 判断文件大小是否超过限制
      if (file.size > this.fileSize * 1024 * 1024) {
        this.$message({
          message: "文件大小不能超过 " + this.fileSize + "MB",
          type: "warning",
        });
        return false;
      }
      this.getWandH(file);
      // 获取文件类型
      const fileType = file.type;
      console.log("文件类型:", file, fileType);
      // 将文件类型传递给父组件
      this.giveMediaType(fileType, this.who, this.applyTarget);
      this.load = true;
      // 等待父组件设置动态参数
      return new Promise((resolve) => {
        // 等待动态参数设置完成
        const checkDynamicParams = () => {
          if (this.dynamicUrl && this.dynamicHeaders && this.dynamicMethod) {
            resolve(true);
          } else {
            setTimeout(checkDynamicParams, 100);
          }
        };
        checkDynamicParams();
      });
    },
    getWandH(file) {
      // 如果是图片类型，获取图片的宽和高
      if (file.type.startsWith("image/") && this.listType === "picture") {
        const reader = new FileReader();
        reader.onload = (e) => {
          const img = new Image();
          img.onload = () => {
            const width = img.width;
            const height = img.height;
            // 将图片宽高信息传递给父组件
            this.$emit("getImageDimensions", { width: width, height: height });
          };
          img.src = e.target.result;
        };
        reader.readAsDataURL(file);
      }
    },
    requeseputOssTempUrl(options) {
      if (
        this.ossId &&
        (typeof this.ossId === "string" || typeof this.ossId === "number")
      ) {
        putOssTempUrl(this.ossId)
          .then((res) => {
            this.load = false;
            if (res.success) {
              // 触发 on-success 事件
              options.onSuccess(res.data);
            }
          })
          .catch((err) => { });
      }
    },
    customUpload(options) {
      this.uploadFile = options.file;
      // console.log("上传文件:", this.uploadFile);
      // 发起请求
      this.$http
        .request({
          method: this.dynamicMethod,
          url: this.dynamicUrl,
          data: this.uploadFile,
          headers: {
            ...this.dynamicHeaders,
          },
        })
        .then((response) => {
          this.requeseputOssTempUrl(options);
        })
        .catch((error) => {
          // 触发 on-error 事件
          options.onError(error);
          this.$message.error("上传文件失败，请重试");
        });
    },
    handleExceed() {
      this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    handleUploadError(err) {
      this.load = false;
      this.$message.error("上传文件失败，请重试");
    },
    handleUploadSuccess(data) {
      // console.log("上传成功:", data);
      let obj = {
        name: this.uploadFile.name,
        url: data.url,
        ossId: this.ossId,
      };
      this.fileList.push(obj);
      this.$emit("input", this.fileList, this.who, this.applyTarget);
    },
    handleRemove(file, fileList) {
      // 移除文件时要把对应的父组件的form.file和imageOidList中的值也删除掉
      this.$emit("deleteFile", file, this.who, this.applyTarget);
    },
    // 当外层的动态参数获取失败，则需要手动将刚刚准备上传（还没有上传成功的）的文件从列表中移除
    handleCleanadd() {
      // 过滤掉没有ossId或url的文件（即未成功上传的文件）
      this.fileList = this.fileList.filter((file) => file.ossId || file.url);
      // 触发input事件通知父组件更新
      this.$emit("input", this.fileList, this.who);
    },
    giveMediaType(fileType, who, applyTarget) {
      this.$emit("giveMediaType", fileType, who, applyTarget);
    },
    loadUploadParams(data) {
      this.uploadParams = {
        path: "",
        name: "",
        permission: "tenant",
        suffix: "",
        mediaType: "",
        sizeLimit: "",
        attachment: "",
        ...data,
      };
      this.requestpostOssUpload();
    },
    resetDynamic() {
      this.dynamicHeaders = null;
      this.dynamicMethod = null;
      this.dynamicUrl = null;
      this.ossId = "";
    },
    requestpostOssUpload() {
      postOssUpload(this.uploadParams)
        .then((res) => {
          if (res.success) {
            this.dynamicHeaders = res.data.headers || {};
            this.dynamicMethod = res.data.method || "PUT";
            this.dynamicUrl = res.data.uploadUrl || "";
            this.ossId = res?.data?.ossId ?? null;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-upload-dragger {
  width: auto;
  height: auto;
}

.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
